<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04-文字</title>
  <style>
    body {
      background-color: #000;
      text-align: center;
    }

    #c1 {
      background-color: #fff;
    }
  </style>
</head>

<body>
  <canvas id="c1" width="1600" height="900"></canvas>

  <script>
    window.onload = function () {
      const oC = document.getElementById('c1')
      const gd = oC.getContext('2d')

      const startX = 400
      const startY = 300
      // 行高
      const lineHeight = 10
      // const str = 'hello world'
      // const str = 'jerry fury'
      const str = '涨幅'

      gd.beginPath()
      // font样式设置与css相同
      // gd.font = lineHeight + 'px serif'
      gd.font = lineHeight + 'px sans-serif'
      // gd.font = lineHeight + 'px Arial'
      // gd.font = lineHeight + 'px SimHei'
      // gd.font = lineHeight + 'px Microsoft Yahei'
      

      const text = gd.measureText(str)
      // 文字实际的边界：上、下、左、右。以及宽度
      console.log(text.actualBoundingBoxAscent)
      console.log(text.actualBoundingBoxDescent)
      console.log(text.actualBoundingBoxLeft)
      console.log(text.actualBoundingBoxRight)
      console.log(text.width)

      // 文本边框线距离实际文本底部或顶部的距离
      const padding = text.actualBoundingBoxDescent || Math.ceil((text.actualBoundingBoxAscent + text.actualBoundingBoxDescent) / 7)
      const margin = 5

      const height = text.actualBoundingBoxAscent + text.actualBoundingBoxDescent

      // 文字填充颜色
      gd.fillStyle = 'red'
      gd.fillText(str, startX + margin, startY - padding - margin)
      gd.fillText(str, startX - text.width - margin, startY - padding - margin)
      gd.fillText(str, startX + margin, startY + height - padding + margin)
      gd.fillText(str, startX - text.width - margin, startY + height - padding + margin)

      gd.stokeStyle = 'skyblue'
      gd.beginPath()
      gd.moveTo(startX, startY - 1000)
      gd.lineTo(startX, startY + 1000)
      gd.stroke()
      gd.beginPath()
      gd.moveTo(startX - 1000, startY)
      gd.lineTo(startX + 1000, startY)
      gd.stroke()


      // 1. 创建img元素
      const img = new Image()
      // 2. 图片加载完成后显示
      img.onload = function () {
        gd.drawImage(img, 500, 500, 1155 / 1.2, 439 / 1.2)
      }
      // 3. 设置图片源地址
      img.src = 'text.png'
    }
  </script>
</body>

</html>